const { User } = require('../models');
const { generateToken, generateUniqueId } = require('../utils/authUtils');
const { validationResult } = require('express-validator');

// 用户登录
const login = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { username, password } = req.body;
    
    // 查找用户
    const user = await User.findOne({ where: { username } });
    
    if (!user || !(await user.validatePassword(password))) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    // 生成令牌
    const token = generateToken(user);

    res.status(200).json({
      token,
      user: {
        id: user.id,
        username: user.username,
        avatar: user.avatar,
        bio: user.bio,
        following: user.following,
        followers: user.followers,
        membership_level: user.membership_level,
        membership_expiry: user.membership_expiry,
        points: user.points
      }
    });
  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 用户注册
const register = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { username, password, avatar, bio } = req.body;

    // 检查用户名是否已存在
    const existingUser = await User.findOne({ where: { username } });
    if (existingUser) {
      return res.status(400).json({ message: '用户名已存在' });
    }

    // 创建用户
    const newUser = await User.create({
      id: generateUniqueId(),
      username,
      password,
      avatar: avatar || `https://picsum.photos/200/200?random=${Math.floor(Math.random() * 100)}`,
      bio: bio || '',
      following: 0,
      followers: 0,
      membership_level: 0,
      points: 0
    });

    // 生成令牌
    const token = generateToken(newUser);

    res.status(201).json({
      token,
      user: {
        id: newUser.id,
        username: newUser.username,
        avatar: newUser.avatar,
        bio: newUser.bio
      }
    });
  } catch (error) {
    console.error('注册失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取用户信息
const getUserInfo = async (req, res) => {
  try {
    const { id } = req.params;
    
    const user = await User.findByPk(id);
    
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    res.status(200).json({
      id: user.id,
      username: user.username,
      avatar: user.avatar,
      bio: user.bio,
      following: user.following,
      followers: user.followers,
      membership_level: user.membership_level,
      membership_expiry: user.membership_expiry,
      points: user.points,
      created_at: user.created_at
    });
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 更新用户信息
const updateUserInfo = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { id } = req.params;
    const { avatar, bio } = req.body;

    // 检查权限
    if (id !== req.user.id) {
      return res.status(403).json({ message: '没有权限修改此用户信息' });
    }

    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 更新用户信息
    await user.update({ avatar, bio });

    res.status(200).json({
      id: user.id,
      username: user.username,
      avatar: user.avatar,
      bio: user.bio,
      following: user.following,
      followers: user.followers
    });
  } catch (error) {
    console.error('更新用户信息失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 更新密码
const updatePassword = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { id } = req.params;
    const { oldPassword, newPassword } = req.body;

    // 检查权限
    if (id !== req.user.id) {
      return res.status(403).json({ message: '没有权限修改此用户密码' });
    }

    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 验证旧密码
    if (!(await user.validatePassword(oldPassword))) {
      return res.status(400).json({ message: '旧密码错误' });
    }

    // 更新密码
    await user.update({ password: newPassword });

    res.status(200).json({ message: '密码更新成功' });
  } catch (error) {
    console.error('更新密码失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 管理员获取所有用户
const getAllUsers = async (req, res) => {
  try {
    const { page = 1, limit = 10, search = '' } = req.query;
    
    const offset = (page - 1) * limit;
    
    const where = {};
    if (search) {
      where.username = { [Op.like]: `%${search}%` };
    }

    const { count, rows: users } = await User.findAndCountAll({
      where,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['created_at', 'DESC']]
    });

    res.status(200).json({
      users: users.map(user => ({
        id: user.id,
        username: user.username,
        avatar: user.avatar,
        membership_level: user.membership_level,
        points: user.points,
        created_at: user.created_at
      })),
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      totalPages: Math.ceil(count / limit)
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 管理员更新用户会员信息
const updateUserMembership = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { id } = req.params;
    const { membership_level, membership_expiry, points } = req.body;

    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 更新会员信息
    await user.update({
      membership_level,
      membership_expiry,
      points
    });

    res.status(200).json({
      message: '会员信息更新成功',
      user: {
        id: user.id,
        username: user.username,
        membership_level: user.membership_level,
        membership_expiry: user.membership_expiry,
        points: user.points
      }
    });
  } catch (error) {
    console.error('更新会员信息失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  login,
  register,
  getUserInfo,
  updateUserInfo,
  updatePassword,
  getAllUsers,
  updateUserMembership
};